<?php
$pid = $_GET['pid'] ?? '';
if (!$pid || !is_dir("data/project_$pid")) {
    echo '项目不存在或未指定';
    exit;
}

function getData($file, $default = []) {
    return file_exists($file) ? json_decode(file_get_contents($file), true) : $default;
}

// 获取项目信息
$projects = getData('data/projects.json');
$projectLanguage = $projects[$pid]['language'] ?? 'zh';

// 获取语言参数，优先使用URL参数，其次使用项目默认语言
$lang = $_GET['lang'] ?? $projectLanguage;

// 访问量统计（分项目）
$statFile = "data/stat_{$pid}.json";
$stat = file_exists($statFile) ? json_decode(file_get_contents($statFile), true) : ['visit'=>0,'download'=>0];
$stat['visit']++;
file_put_contents($statFile, json_encode($stat, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));

$dir = "data/project_$pid/";
$appInfo = getData($dir.'app_info.json');
$screens = getData($dir.'screenshots.json');
$versions = getData($dir.'versions.json');
$links = getData($dir.'links.json');
$icon = isset($appInfo['icon']) && file_exists($appInfo['icon']) ? $appInfo['icon'] : 'assets/fonts/fontawesome-webfont.svg';

// 根据语言选择显示内容
$isEnglish = $lang === 'en';
$appName = $isEnglish ? ($appInfo['name_en'] ?? $appInfo['name'] ?? '') : ($appInfo['name'] ?? '');
$appDesc = $isEnglish ? ($appInfo['desc_en'] ?? $appInfo['desc'] ?? '') : ($appInfo['desc'] ?? '');
$appDeveloper = $isEnglish ? ($appInfo['developer_en'] ?? $appInfo['developer'] ?? '') : ($appInfo['developer'] ?? '');

// 语言文本
$texts = [
    'zh' => [
        'title' => 'APP下载引导',
        'provided_by' => '由',
        'provided_by_suffix' => '提供',
        'get' => '获取',
        'qr_tip' => '永久二维码，扫码在手机上下载',
        'version' => '版本：',
        'update' => '更新：',
        'platform' => '平台：',
        'app_intro' => '应用简介：',
        'tip' => '适用于Android和iOS设备',
        'privacy_policy' => '隐私政策',
        'history_versions' => '历史版本',
        'help_center' => '帮助中心',
        'user_agreement' => '用户协议',
        'history_title' => '历史版本下载',
        'version_number' => '版本号：',
        'update_time' => '更新时间：',
        'download' => '下载',
        'close' => '关闭',
        'project_not_exist' => '项目不存在或未指定'
    ],
    'en' => [
        'title' => 'APP Download',
        'provided_by' => 'Provided by',
        'provided_by_suffix' => '',
        'get' => 'Get',
        'qr_tip' => 'Permanent QR code, scan to download on mobile',
        'version' => 'Version: ',
        'update' => 'Updated: ',
        'platform' => 'Platform: ',
        'app_intro' => 'App Description:',
        'tip' => 'Available for Android and iOS devices',
        'privacy_policy' => 'Privacy Policy',
        'history_versions' => 'Version History',
        'help_center' => 'Help Center',
        'user_agreement' => 'User Agreement',
        'history_title' => 'Version History Download',
        'version_number' => 'Version: ',
        'update_time' => 'Updated: ',
        'download' => 'Download',
        'close' => 'Close',
        'project_not_exist' => 'Project does not exist or not specified'
    ]
];

$t = $texts[$lang] ?? $texts['zh'];
?>
<!DOCTYPE html>
<html lang="<?=$lang?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?=htmlspecialchars($appName ?: $t['title'])?></title>
    <link rel="stylesheet" href="assets/css/main.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <script>
    // 仅保留下载量统计，无微信判断
    document.getElementById('download-link').onclick = function() {
        fetch('stat.php?type=download&pid=<?=urlencode($pid)?>');
    };
    </script>
    <div class="container" id="main-content">
        <img src="<?=$icon?>" alt="App Icon" class="app-icon">
        <div class="app-name"><?=htmlspecialchars($appName)?></div>
        <div class="app-rating">
            <span class="star">★</span><span class="star">★</span><span class="star">★</span><span class="star">★</span><span class="star">☆</span>
            <span class="rating-num"><?=htmlspecialchars($appInfo['rating']??'')?></span>
        </div>
        <div class="app-meta"><?=$t['provided_by']?> <b><?=htmlspecialchars($appDeveloper)?></b><?=$t['provided_by_suffix']?></div>
        <a href="<?=htmlspecialchars($versions[0]['url']??'#')?>" class="download-btn" id="download-link"><?=$t['get']?></a>
        <div class="qr-section">
            <img src="qrcode.php?text=<?=urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off'?'https':'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'])?>" alt="二维码下载" class="qr-img">
            <div class="qr-tip"><?=$t['qr_tip']?></div>
        </div>
        <div class="meta-list">
            <div class="meta-item"><span class="meta-label"><?=$t['version']?></span><?=htmlspecialchars($versions[0]['version']??'')?></div>
            <div class="meta-item"><span class="meta-label"><?=$t['update']?></span><?=htmlspecialchars($versions[0]['date']??'')?></div>
            <div class="meta-item"><span class="meta-label"><?=$t['platform']?></span>Android / <s>iOS</s></div>
        </div>
        
        <div class="screenshot-carousel" id="carousel">
            <div class="carousel-track" id="carousel-track">
                <?php foreach($screens as $img): ?>
                <img src="data/project_<?=$pid?>/screenshots/<?=htmlspecialchars($img)?>" class="carousel-img" alt="APP界面">
                <?php endforeach; ?>
            </div>
            <button class="carousel-btn left" id="carousel-prev">&#8592;</button>
            <button class="carousel-btn right" id="carousel-next">&#8594;</button>
        </div>
        
        <div class="app-desc">
            <b><?=$t['app_intro']?></b><br>
            <?=nl2br(htmlspecialchars($appDesc))?>
        </div>
        
        <div class="tip"><?=$t['tip']?></div>
        
        <a href="<?=htmlspecialchars($links['privacy']??'#')?>" class="policy-link" target="_blank"><?=$t['privacy_policy']?></a>
        <div class="footer-links">
            <a href="#" class="footer-link" id="history-link"><?=$t['history_versions']?></a>
            <span class="footer-sep">|</span>
            <a href="<?=htmlspecialchars($links['help']??'#')?>" class="footer-link" target="_blank"><?=$t['help_center']?></a>
            <span class="footer-sep">|</span>
            <a href="<?=htmlspecialchars($links['agreement']??'#')?>" class="footer-link" target="_blank"><?=$t['user_agreement']?></a>
        </div>
        <div class="modal-mask" id="history-modal-mask" style="display:none;"></div>
        <div class="history-modal" id="history-modal" style="display:none;">
            <div class="history-modal-title"><?=$t['history_title']?></div>
            <div class="history-list">
                <?php foreach($versions as $v): ?>
                <div class="history-item">
                    <div class="history-info">
                        <div class="history-appname"><?=htmlspecialchars($v['name']??'')?></div>
                        <div class="history-meta"><?=$t['version_number']?><?=htmlspecialchars($v['version']??'')?>　|　<?=$t['update_time']?><?=htmlspecialchars($v['date']??'')?></div>
                    </div>
                    <a href="<?=htmlspecialchars($v['url']??'#')?>" class="history-download" target="_blank"><?=$t['download']?></a>
                </div>
                <?php endforeach; ?>
            </div>
            <button class="history-close" id="history-close"><?=$t['close']?></button>
        </div>
    </div>
    <script>
        aVersion = '<?=htmlspecialchars($versions[0]['version']??'')?>';
    // 轮播图逻辑
    (function () {
        var track = document.getElementById('carousel-track');
        var prev = document.getElementById('carousel-prev');
        var next = document.getElementById('carousel-next');
        var idx = 0;
        function update() {
            var imgs = track.getElementsByClassName('carousel-img');
            if(imgs.length) track.style.transform = 'translateX(' + (-idx * track.offsetWidth) + 'px)';
        }
        function go(n) {
            var imgs = track.getElementsByClassName('carousel-img');
            if(!imgs.length) return;
            idx = (n + imgs.length) % imgs.length;
            update();
        }
        prev.onclick = function () { go(idx - 1); };
        next.onclick = function () { go(idx + 1); };
        // 触摸滑动
        var startX = 0, deltaX = 0;
        track.addEventListener('touchstart', function (e) {
            startX = e.touches[0].clientX;
        });
        track.addEventListener('touchmove', function (e) {
            deltaX = e.touches[0].clientX - startX;
        });
        track.addEventListener('touchend', function () {
            if (deltaX > 40) go(idx - 1);
            else if (deltaX < -40) go(idx + 1);
            deltaX = 0;
        });
        window.addEventListener('resize', update);
        setInterval(update, 500);
    })();
    // 历史版本弹窗逻辑
    var historyLink = document.getElementById('history-link');
    var historyModal = document.getElementById('history-modal');
    var historyMask = document.getElementById('history-modal-mask');
    var historyClose = document.getElementById('history-close');
    function closeHistoryModal() {
        historyModal.style.display = 'none';
        historyMask.style.display = 'none';
    }
    historyLink.onclick = function (e) {
        e.preventDefault();
        historyModal.style.display = 'block';
        historyMask.style.display = 'block';
    };
    historyClose.onclick = closeHistoryModal;
    historyMask.onclick = closeHistoryModal;
    </script>
</body>
</html> 